package com.tokenplus.thai.utils

import com.tokenplus.thai.adata.checkin.CurrentMonthInfo
import java.text.SimpleDateFormat
import java.time.YearMonth
import java.util.Calendar;
import java.util.Locale

object CalendarUtil {

    /**
     * 获得指定月份的天数
     */
    fun getDaysInMonth(year: Int, month: Int): Int {
//        return YearMonth.of(year, month).lengthOfMonth()

        val calendar = Calendar.getInstance()
        calendar.set(Calendar.YEAR, year)
        calendar.set(Calendar.MONTH, month - 1) // Calendar月份是从0开始的，所以需要减1
        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH)

//        val calendar = Calendar.getInstance()
//        calendar.set(Calendar.YEAR, year)
//        calendar.set(Calendar.MONTH, month)
//        return calendar.getActualMaximum(Calendar.DAY_OF_MONTH)
    }

    /**
     * 获得指定日期的星期
     */
    fun getDayOfWeek(year: Int, month: Int, day: Int): Int {
        val monthFormat = if (month >= 10) {
            month.toString()
        } else {
            "0$month"
        }

        val dayFormat = if (day >= 10) {
            day.toString()
        } else {
            "0$day"
        }

        val formatter = SimpleDateFormat("yyyy-MM-dd", Locale.getDefault())
        val date = formatter.parse("$year-$monthFormat-$dayFormat") ?: return 0
        val calendar = Calendar.getInstance()
        calendar.time = date

        //1日 2一 3二 4三 5四 6五 7六
        //1一
        var week = calendar.get(Calendar.DAY_OF_WEEK)
        if (week < 2) {
            week = 6
        } else {
            week -= 2
        }
        println("getDayOfWeek-year:$year month:$month day:$day week:$week")
        return week
    }

    /**
     * 获取当月信息
     */
    fun getCurMonthInfo(): CurrentMonthInfo {
        val calendar = Calendar.getInstance()
        val month = calendar.get(Calendar.MONTH) + 1
        val year = calendar.get(Calendar.YEAR)
        val curDay = calendar.get(Calendar.DAY_OF_MONTH)
        val days = getDaysInMonth(year, month)
        val firstDayWeek = getDayOfWeek(year, month, 1)
        return CurrentMonthInfo(
            firstDayWeek = firstDayWeek.toString(),
            days = days,
            year = year,
            month = month,
            curDay = curDay.toString()
        )
    }
}
